package com.thinkingstar.iads.projectcenter.controller;

import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.common.utils.*;
import com.thinkingstar.iads.datacenter.entity.*;
import com.thinkingstar.iads.datacenter.entity.common.dao.CommonDao;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcFormField;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectDesignCell;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectDesignPhase;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectMention;
import com.thinkingstar.iads.datacenter.serviceImpl.DataDesignManagerServiceImpl;
import com.thinkingstar.iads.projectcenter.entity.*;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectData;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectFile;
import com.thinkingstar.iads.projectcenter.serviceImpl.ProjectDesignManagerServiceImpl;
import com.thinkingstar.iads.projectcenter.serviceImpl.ProjectSjpsServiceImpl;
import com.zhuozhengsoft.pageoffice.*;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegionInsertType;
import com.zhuozhengsoft.pageoffice.wordwriter.DataTag;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;
import net.sf.ehcache.transaction.xa.EhcacheXAException;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * 设计评审相关
 * @author z
 *
 */
@IocBean
@At("/projectCenter/sjps")
@Filters({ @By(type = GlobalsFilter.class) , @By(type = UserLoginFilter.class)})
public class ProjectSjpsController {

    private static Log log = Logs.get();

    @Inject
    DataDesignManagerServiceImpl dataDesignManagerServiceImpl;

    @Inject
    ProjectSjpsServiceImpl projectSjpsService;

    @Inject
    private DaoDcProjectMention daoDcProjectMention;

    @Inject
    private DaoDcProjectDesignCell daoDcProjectDesignCell;

    @Inject
    CommonDao commonDao;

    @Inject
    DaoPcProjectFile daoPcProjectFile;

    @Inject
    DaoPcProjectData daoPcProjectData;

    @Inject
    private DaoDcProjectDesignPhase daoDcProjectDesignPhase;

    @Inject
    private DaoDcFormField daoDcFormField;

    @Inject
    private ProjectDesignManagerServiceImpl projectDesignManagerServiceImpl;

    /**
     * 点击设计评审 进入页面
     * */
    @At("/index/?")
    @Ok("beetl:/projectRoot/pcCenter/sjps/index.html")
    public NutMap index(String project_id) {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        List<Map> list = projectSjpsService.getDcTemplateVersionList(nutMap);
        //获取这个阶段所有提入资料 里的非结构化文件
        List<NutMap> listNew = projectSjpsService.getMentionFjghByPhaseAndContentId(nutMap);
        //获取这个阶段所有提入资料 里的结构化文件
        List<NutMap> listNew2 = projectSjpsService.getMentionJghByPhaseAndContentId(nutMap);

        PcProjectInfo projectInfo = daoPcProjectData.fetch(project_id);
        List<NutMap> trzl = new ArrayList<NutMap>();
        if (projectInfo.getProject_design_content_name().equals("动车运用所")){
            for (int i=0;i<listNew.size();i++){
                String fileName = (String)listNew.get(i).get("mention_information_name");
                if (fileName.equals("车站表")){
                    listNew.get(i).put("mention_information_name","附件04 车站表");
                    trzl.add(listNew.get(i));
                } else if (fileName.equals("上阶段审查意见")){
                    listNew.get(i).put("mention_information_name","附件01 上阶段审查意见");
                    trzl.add(listNew.get(i));
                }
            }
            for (int i=0;i<listNew2.size();i++){
                String fileName = (String)listNew2.get(i).get("mention_information_name");
                 if (fileName.equals("旅客列车对数表")){
                     listNew2.get(i).put("mention_information_name","附件05 旅客列车对数表");
                    trzl.add(listNew2.get(i));
                }
            }
            nutMap.put("listNew",trzl);
        } else {
            nutMap.put("listNew",listNew);
        }
        nutMap.put("list",list);
        nutMap.put("projectInfo",projectInfo);
        return nutMap;
    }


    //非结构化提入资料查看
    @At("/mentionDetail/?/?")
    @Ok("beetl:/projectRoot/pcCenter/sjps/mentionDetail.html")
    public Object mentionDetail(String project_id,String mention_id, HttpServletRequest request){
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("mention_id",mention_id);
        return nutMap;
    }

    //结构化提入资料查看
    @At("/mentionDetailJgh/?/?")
    @Ok("beetl:/projectRoot/pcCenter/sjps/mentionDetailJgh.html")
    public Object mentionDetailJgh(String project_id,String mention_id, HttpServletRequest request){
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("mention_id",mention_id);
        return nutMap;
    }

    //非结构化提入资料查看
    @At("/mentionDetailData")
    @Ok("json:full")
    public Object mentionDetailData(@Param("..") NutMap param , HttpServletRequest request){
        try {
            return projectDesignManagerServiceImpl.mentionDataManageForSjps(param,request);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常,请重试!");
        }
    }

    /**
     *查询 设计评审 文件列表
     * */
    @At("/queryFileList")
    @Ok("json:full")
    public Object queryFileList(@Param("..") NutMap param, HttpServletRequest request, HttpServletResponse response){
        //查询数据中心 设计评审资料库
        return projectSjpsService.findSjpsTemplateList(param);
    }

    /**
     * 点击去合成 进入页面
     * */
    @At("/toMerge/?/?")
    @Ok("beetl:/projectRoot/pcCenter/sjps/merge.html")
    public NutMap toMerge(String project_id,String wjid, HttpServletRequest req , HttpServletResponse rep)  throws IOException {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("wjid",wjid);

        //根据id查询 合成规则
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);

        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcSjpsFile sjpsFile = projectSjpsService.getPcSjpsFile(project_id,dcTemplateVersion.getTemplate_code());

        //合成规则str
        String compound_rule = "";
        if (null!=sjpsFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = sjpsFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcTemplateVersion.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();
        //提入资料
        String mention_data_id = dcTemplateVersion.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料 结构化
            } else {
                data.setType("trzl_fjgh");//非提入资料 结构化
            }

            if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+mentionList.get(i).getMention_information_name()+"------------");
            exportMentionExcelData(project_id,mentionList.get(i).getId(),req,rep);
        }

        //根据提入资料id获取提入资料
        String mention_data = projectSjpsService.getMentionDataByIds(mention_data_id);
        nutMap.put("mention_data",mention_data);

        //设计单元
        String design_cell_id = dcTemplateVersion.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+designcell.get(i).getDesign_cell_table_code()+"------------");
            exportDesignCellExcelData(project_id,designcell.get(i).getId(),req,rep);
        }

        //根据设计单元id获取设计单元
        String design_cell_data = projectSjpsService.getDesignCellByIds(design_cell_id);
        nutMap.put("design_cell_data",design_cell_data);

        //根据项目id查询 项目所有常量
        List<PcProjectConstantData> constantData = projectSjpsService.getConstantData(project_id);

        //根据模板id获取模板列表
        String template_id = dcTemplateVersion.getCompound_template();
        List<DcCompoundTemplate> template = projectSjpsService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            if (compound_rule.contains(template.get(i).getTemplate_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
        }
        nutMap.put("list",mergeData);
        nutMap.put("compound_rule",compound_rule);
        return nutMap;
    }

    /**
     * 保存合成规则
     * */
    @At("/saveSorting/?/?")
    @Ok("json:full")
    public Object saveSorting(String project_id,String wjid,String sorting) {
        //根据id查询 合成规则
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);
        projectSjpsService.insertOrUpdatePcSjpsFile(project_id,sorting,dcTemplateVersion.getTemplate_code());
        return AjaxResult.success();
    }

    /**
     * 手动保存合成规则  2019/01/23
     *
     * */
    public void saveSortingNew(String project_id,String wjid,HttpServletResponse resp,HttpServletRequest req) throws Exception{
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("wjid",wjid);

        //根据id查询 合成规则
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);

        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcSjpsFile sjpsFile = projectSjpsService.getPcSjpsFile(project_id,dcTemplateVersion.getTemplate_code());

        //合成规则str
        String compound_rule = "";
        if (null!=sjpsFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = sjpsFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcTemplateVersion.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();
        //提入资料
        String mention_data_id = dcTemplateVersion.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料 结构化
            } else {
                data.setType("trzl_fjgh");//非提入资料 结构化
            }

            if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+mentionList.get(i).getMention_information_name()+"------------");
            exportMentionExcelData(project_id,mentionList.get(i).getId(),req,resp);
        }

        //根据提入资料id获取提入资料
        String mention_data = projectSjpsService.getMentionDataByIds(mention_data_id);
        nutMap.put("mention_data",mention_data);

        //设计单元
        String design_cell_id = dcTemplateVersion.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+designcell.get(i).getDesign_cell_table_code()+"------------");
            exportDesignCellExcelData(project_id,designcell.get(i).getId(),req,resp);
        }

        //根据设计单元id获取设计单元
        String design_cell_data = projectSjpsService.getDesignCellByIds(design_cell_id);
        nutMap.put("design_cell_data",design_cell_data);

        //根据项目id查询 项目所有常量
        List<PcProjectConstantData> constantData = projectSjpsService.getConstantData(project_id);

        //根据模板id获取模板列表
        String template_id = dcTemplateVersion.getCompound_template();
        List<DcCompoundTemplate> template = projectSjpsService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            if (compound_rule.contains(template.get(i).getTemplate_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
        }
        nutMap.put("list",mergeData);
        nutMap.put("compound_rule",compound_rule);

        if (compound_rule.contains("null")){
            compound_rule = compound_rule.replace("null","");
        }
        projectSjpsService.insertOrUpdatePcSjpsFile(project_id,compound_rule,dcTemplateVersion.getTemplate_code());
    }
	
//	/**
//	 * 在线预览
//	 * @param file_id
//	 * @param file_id
//	 * @param request
//	 * @return
//	 * @throws FileNotFoundException
//	 */
//	@At("/previewDataFile/?")
//	@Ok("beetl:/projectRoot/pcCenter/pageOffice/merge_word.html")
//	public NutMap previewFile(String file_id , HttpServletRequest request) throws FileNotFoundException{
//		NutMap nutMap = new NutMap();
//        PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
//	    String relative_path = pcProjectFile.getRelativePaths();
//	    String file_path = POIFileUtil.getAbFileNameByRepath(relative_path);
//	    File file = new File(file_path);
//	    Boolean flag = file.exists();
//	    log.debug("文件路径。。。。。。"+file_path);
//	    log.debug("是否生成了文件。。。。。。"+flag);
//	    String file_name = pcProjectFile.getName();
//	    System.out.println(request.getContextPath());
//	    String open_url = request.getContextPath()+"/datacenter/common/getFileStream?file_id="+file_id;
//	    String suffix = file_name.substring(file_name.lastIndexOf(".")+1);
//	    if ("doc".equals(suffix) || "docx".equals(suffix)) {
//	        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
//	        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
//	    	poCtrl.setTagId("DOCCtrl1"); //此行必须
//	    	poCtrl.webOpen(open_url, OpenModeType.docReadOnly, "张三");
//	    	poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
//	    	nutMap.put("pageoffice",poCtrl.getHtmlCode("DOCCtrl1"));
//	    } else if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
//	        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
//	        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
//	    	poCtrl.setTagId("XLSCtrl1"); //此行必须
//	    	poCtrl.webOpen(open_url, OpenModeType.xlsReadOnly, "张三");
//	    	poCtrl.webCreateNew("张三", DocumentVersion.Excel2007);
//	    	nutMap.put("pageoffice",poCtrl.getHtmlCode("XLSCtrl1"));
//	    }  else if("pdf".equals(suffix)){
//	    	PDFCtrl pdfCtrl = new PDFCtrl(request);
//	    	pdfCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
//	    	pdfCtrl.setTagId("PDFCtrl1");
//	    	pdfCtrl.webOpen(open_url);
//	    	nutMap.put("pageoffice",pdfCtrl.getHtmlCode("PDFCtrl1"));
//	    }
//		return nutMap;
//	}

    /**
     *    实现在线预览功能直接网页显示不使用pageoffice预览
     *
     * @param file_id
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @At("/previewDataFile/?")
    @Ok("raw")
    public String previewFile(String file_id , HttpServletRequest request) throws FileNotFoundException{
        String serverIp= InitSystemProperties.get("preview.server.ip");
        String serverPort = InitSystemProperties.get("preview.server.port");
        String previewServer ="http://"+serverIp+":"+serverPort;

        PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
        if(pcProjectFile != null){
            String relative_path = pcProjectFile.getRelativePaths();
            String open_url = previewServer+"/"+FileCommonUtil.pathToURI(relative_path);
            //String open_url = "previewServer"+"/"+FileCommonUtil.pathToURI(relative_path);
            String url = previewServer+"/onlinePreview?url="+open_url;
           // String testurl = "http://192.168.31.100:8082/preview"+"/onlinePreview?url="+"http://192.168.31.100:8082/preview"+"/"+FileCommonUtil.pathToURI(relative_path);
            return url;
        }
        return "";
    }

    /**
     * 点击合成
     * */
    @At("/mergeWord/?/?/?")
    @Ok("beetl:/projectRoot/pcCenter/pageOffice/merge_word.html")
    public NutMap mergeWord(String project_id, String wjid, String hcType, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception{
       saveSortingNew(project_id,wjid,response,request);
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);

        //根据id查询 合成规则
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);

        //hcType =0 合成，hcType=1 重新合成
        //点合成的时候 查询有没有保存 过，如果保存过那么直接取
        //点重新合成，那么就不管原来的文件，直接走合成流程
        if (hcType.equals("0")) {
            //判断是否已经保存过，保存过，那么直接取 保存过的合成文档，不需要重新合成
            String filePath = POIFileUtil.getFilePathByType("设计评审",project_id)+dcTemplateVersion.getTemplate_name()+".docx";
            File file = new File(filePath);
            if (file.exists()){
                //文件存在  说明合成过
                PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
                poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
                poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
                poCtrl.setSaveFilePage(request.getContextPath()+"/projectCenter/sjps/savefile/"+project_id+"/"+wjid);//设置处理文件保存的请求方法
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved");
                poCtrl.setTheme(ThemeType.Office2010);
                poCtrl.webOpen(request.getContextPath()+"/projectCenter/sjps/downFile/"+"sjps__"+wjid+"/"+project_id,OpenModeType.docNormalEdit,"杨震");
                poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
                poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
                nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
                return nutMap;
            }
        }

        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcSjpsFile sjpsFile = projectSjpsService.getPcSjpsFile(project_id,dcTemplateVersion.getTemplate_code());

        //合成规则str
        String compound_rule = "";
        if (null!=sjpsFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = sjpsFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcTemplateVersion.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();
        List<PcMergeData> mergeDataNew = new ArrayList<>();

        //提入资料
        String mention_data_id = dcTemplateVersion.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料_结构化
            } else {
                data.setType("trzl_fjgh");//提入资料_非结构化
            }
            //if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
            mergeData.add(data);
            //}
        }

        //设计单元
        String design_cell_id = dcTemplateVersion.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            //if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
            mergeData.add(data);
            //}
        }

        //根据项目id查询 项目所有常量
        List<PcProjectConstantData> constantData = projectSjpsService.getConstantData(project_id);

        //根据模板id获取模板列表
        String template_id = dcTemplateVersion.getCompound_template();
        List<DcCompoundTemplate> template = projectSjpsService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            //if (compound_rule.contains(template.get(i).getTemplate_name())) {
            mergeData.add(data);
            //}
        }


        String[] str = compound_rule.split("、");
        for (int j=0;j<str.length;j++) {
            for (int i=0;i<mergeData.size();i++) {
                if (str[j].equals(mergeData.get(i).getFileName())) {
                    mergeDataNew.add(mergeData.get(i));
                }
            }
        }

        WordDocument docx = word(mergeDataNew,project_id,request,response);

        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
        poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
        poCtrl.setSaveFilePage(request.getContextPath()+"/projectCenter/sjps/savefile/"+project_id+"/"+wjid);//设置处理文件保存的请求方法
        poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved");
        poCtrl.setTheme(ThemeType.Office2010);
        poCtrl.setWriter(docx);
        poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
        poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
        nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
        return nutMap;
    }

    //导出提入资料excel和word数据
    public void exportMentionExcelData(String project_id,String mention_data_id , HttpServletRequest req , HttpServletResponse rep) throws IOException {
        DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(mention_data_id);
        String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
        List<NutMap> dataList = commonDao.findOrderDataListByTableName(project_id,table_name);
        List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
        String file_name = dcProjectMentionInformation.getMention_information_name()+".xls";
        String word_name = dcProjectMentionInformation.getMention_information_name()+".docx";
        System.out.println("create exportMentionExcelData start------------"+table_name+"--------------------"+file_name+"----------"+word_name+"------------");
        List<Map> countList = daoDcFormField.countField(field_list,table_name,project_id);
        if (dcProjectMentionInformation.getMention_information_type()){//结构化数据表单
            File docx_file = ExcelPoiUtil.createWordAddCount(word_name,project_id,"提入资料_jgh",field_list,dataList,countList);
            File excel_file = ExcelPoiUtil.createExcelAddCount(file_name, project_id,"提入资料_jgh",field_list,dataList,countList);
        }
    }

    //导出设计单元excel和word数据
    public void exportDesignCellExcelData(String project_id,String design_cell_id , HttpServletRequest req , HttpServletResponse rep) throws IOException {
        DcProjectDesignCell dcProjectDesignCell = daoDcProjectDesignCell.fetch(design_cell_id);
        String table_name = new StringBuffer("dc_designcell_").append(dcProjectDesignCell.getDesign_cell_table_code()).toString();
        List<NutMap> dataList = commonDao.findOrderDataListByTableName(project_id,table_name);
        List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
        String file_name = dcProjectDesignCell.getDesign_cell_table_name()+".xls";
        String word_name = dcProjectDesignCell.getDesign_cell_table_name()+".docx";
        System.out.println("create exportDesignCellExcelData start---------"+table_name+"------------------------"+file_name+"----------"+word_name+"------------");
        List<Map> countList = daoDcFormField.countField(field_list,table_name,project_id);
        File docx_file = ExcelPoiUtil.createWordAddCount(word_name,project_id,"设计单元",field_list,dataList,countList);
        File excel_file = ExcelPoiUtil.createExcelAddCount(file_name,project_id,"设计单元",field_list,dataList,countList);
    }

    public WordDocument word(List<PcMergeData> data ,String project_id , HttpServletRequest request,HttpServletResponse response){
        boolean ok = true;
        String str = "";
        String msg = "";
        Map<String,String> map = new HashMap<>();
        String sysPath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator;
        Map<String,String> params = new HashMap<>();
        List<PcMergeData> dataNew = new ArrayList<>();
        for (int i=0;i<data.size();i++) {
            dataNew.add(data.get(i));
        }

        for (int i=0;i<data.size();i++) {
            String filePath = "";
            File file = null;
            if (data.get(i).getType().equals("trzl_jgh")) {//提入资料
                filePath = "trzl_jgh__"+data.get(i).getId();
                file = new File(POIFileUtil.getFilePathByType("提入资料_jgh",project_id)+data.get(i).getFileName()+".docx");
                if(!file.exists()){
                    msg += data.get(i).getFileName()+" 该文件不存在，请确认上传成功\n ";
                    ok = false;
                } else {
                    map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                }
            } else if (data.get(i).getType().equals("trzl_fjgh")){
                DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(data.get(i).getId());
                String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
                List<NutMap> dataList = commonDao.findOrderDataListByTableName(project_id,table_name);
                List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);

                for (int n=0;n<field_list.size();n++) {
                    for (int m=0;m<dataList.size();m++) {
                        String value = dataList.get(m).getString(field_list.get(n).getString("field_name"));
                        //将非结构化字段值去 pc_project_file中查询，如果有就说明是文件，如果没有说明是普通字段
                       if (null!=value){
                           PcProjectFile pcFile = daoPcProjectFile.fetch(value);
                           if ( null != pcFile && pcFile.getId().equals(value)) {
                               filePath = "trzl_fjgh__"+pcFile.getId();
                               String paths = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+pcFile.getRelativePaths();
                               file = new File(paths);
                               PcMergeData pc = new PcMergeData();
                               pc.setType("trzl_fjgh");
                               pc.setFileName(pcFile.getName());
                               pc.setId(pcFile.getId());
                               pc.setFileNum(field_list.get(n).getString("field_name"));

                               if (pcFile.getFileExt().equals("docx")||pcFile.getFileExt().equals("doc")) {
                                   dataNew.add(pc);
                                   if(!file.exists()){
                                       msg += pcFile.getName()+" 该文件不存在，请确认上传成功\n ";
                                       ok = false;
                                   } else {
                                   /* String ext = filePath.substring(filePath.lastIndexOf(".") + 1);
                                    String name = filePath.substring(0,filePath.lastIndexOf("."));*/
                                       map.put(pcFile.getName(),request.getContextPath()+"/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                       // map.put(pcFile.getName().substring(0,pcFile.getName().lastIndexOf(".")),"/iads/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                   }
                               } else if (pcFile.getFileExt().equals("jpg")||pcFile.getFileExt().equals("png")) {
                                   dataNew.add(pc);
                                   //String name = filePath.split(".")[0];
                                   //String ext = filePath.split(".")[1];
                                /*String ext = filePath.substring(filePath.lastIndexOf(".") + 1);
                                String name = filePath.substring(0,filePath.lastIndexOf("."));*/
                                   if(!file.exists()){
                                       msg += pcFile.getName()+" 该文件不存在，请确认上传成功\n ";
                                       ok = false;
                                   } else {
                                       //map.put(pcFile.getName().substring(0,pcFile.getName().lastIndexOf(".")),"/iads/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                       map.put(pcFile.getName(),request.getContextPath()+"/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                   }
                               }
                           }
                       }

                    }
                }
				/*filePath =
				file = new File()*/
            } else if (data.get(i).getType().equals("sjdy")) {//设计单元
                filePath = "sjdy__"+data.get(i).getId();
                file = new File(POIFileUtil.getFilePathByType("设计单元",project_id)+data.get(i).getFileName()+".docx");
                if(!file.exists()){
                    msg += data.get(i).getFileName()+" 该文件不存在，请确认上传成功\n ";
                    ok = false;
                } else {
                    map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                }
            } else {//模板
                List<DcCompoundTemplate> ls = projectSjpsService.getTemplateListByIds(data.get(i).getId());
                if (ls.size()>0) {
                    //查询模板
                    List<DcTemplateVariable> variable = projectSjpsService.getTemplateVariable(ls.get(0).getId());
                    //模板里塞值
                    params.putAll(projectSjpsService.getVariableValues(variable,project_id));
                    filePath = "mb__"+ls.get(0).getId();
                    file = new File(sysPath+ls.get(0).getTemplate_file_path());
                    if(!file.exists()){
                        msg += data.get(i).getFileName()+" 该模板文件不存在，请确认上传成功\n ";
                        ok = false;
                    } else {
                        map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                    }
                }
            }
        }

        WordDocument docx = new WordDocument();  //这里需要按照文件名单顺序进行排序

        if(ok){
            int num = 1;
            String home = "[home]";
            DataRegion dr = null;
            for (int i = 0; i < dataNew.size(); i++) {
                if(i != 0){
                    home = "reg"+String.valueOf(num - 1);
                }
                if(StringUtils.isNotEmpty(map.get(dataNew.get(i).getFileName()))){
                    dr = docx.createDataRegion("reg"+num, DataRegionInsertType.After,home);
                    dr.setEditing(true);
                    DataRegion doc = docx.openDataRegion("PO_reg" + num);
                    if (dataNew.get(i).getFileName().endsWith("png")||dataNew.get(i).getFileName().endsWith("jpg")) {
                        doc.setValue("[image]" + map.get(dataNew.get(i).getFileName()) + "[/image]");
                    } else {
                        doc.setValue("[word]" + map.get(dataNew.get(i).getFileName()) + "[/word]");
                    }

                } else {
                    dr = docx.createDataRegion("reg"+num, DataRegionInsertType.After,home);
                    dr.setEditing(true);
                    DataRegion doc = docx.openDataRegion("PO_reg" + num);
                    doc.setValue("");
                }
                num++;
            }
        }else{
            DataRegion dr = docx.createDataRegion("msg", DataRegionInsertType.After,"[home]");
            dr.setEditing(true);
            dr.getFont().setColor(Color.RED);
            DataRegion doc = docx.openDataRegion("msg");
            doc.setValue(msg);

        }
        Set<String> keys = params.keySet();
        for(String key:keys){
            String type = key.split("__")[1];
            String k = key.split("__")[0];
            if (type.equals("DataRegion")){
                DataRegion dataRegion = docx.openDataRegion(k);
                dataRegion.setValue(params.get(k+"__"+type));
                dataRegion.getFont().setItalic(true);
                dataRegion.getShading().setBackgroundPatternColor(Color.gray);
            } else if (type.equals("DataTag")){
                DataTag dataTag = docx.openDataTag(k);
                if(null==params.get(k+"__"+type)){
                    dataTag.setValue("");
                } else {
                    dataTag.setValue(params.get(k+"__"+type));
                }
                dataTag.getFont().setItalic(true);
                dataTag.getShading().setBackgroundPatternColor(Color.gray);
            } else if (type.equals("Image")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据提入资料里的图片id 获取图片路径
                    dataRegion.setValue("[image]"+request.getContextPath()+"/projectCenter/sjps/downFile/trzl_fjgh__"+id+"/"+project_id+"[/image]");
                } else {
                    dataRegion.setValue(k+"图片不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            } else if (type.equals("InputTable")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据提入资料id 获取文件
                    try {
                        exportMentionExcelData(project_id,id,request,response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dataRegion.setValue("[word]"+request.getContextPath()+"/projectCenter/sjps/downFile/trzl_jgh__"+id+"/"+project_id+"[/word]");
                } else {
                    dataRegion.setValue(k+"提入资料不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            } else if (type.equals("DesignTable")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据设计单元id 获取文件
                    try {
                        exportDesignCellExcelData(project_id,id,request,response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dataRegion.setValue("[word]"+request.getContextPath()+"/projectCenter/sjps/downFile/sjdy__"+id+"/"+project_id+"[/word]");
                } else {
                    dataRegion.setValue(k+"设计单元不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            }
        }
        DataTag dataTag = docx.openDataTag("{{项目名称}}");
        DataTag dataTag1 = docx.openDataTag("{{项目阶段}}");
        DataTag dataTag2 = docx.openDataTag("{{当前时间}}");
        PcProjectInfo  pc = daoPcProjectData.fetch(project_id);
        dataTag.setValue(pc.getProject_name());
        dataTag1.setValue(daoDcProjectDesignPhase.fetch(pc.getProject_design_phase_id()).getProject_design_phase_name());
        dataTag2.setValue(CommonDateUtil.formatDate(new Date()));
        return docx;
    }

    /**
     * 预览下载文件
     * @param req
     */
    @GET
    @At("/downFile/?/?")
    @Ok("raw:stream")
    public void downFile(String path ,String project_id,HttpServletRequest req,HttpServletResponse resp){
    	System.out.println("download file sjps fjgh file--------------------------------"+path+"------------");
        String[] str = path.split("__");
        String filePath = "";
        String sysPath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator;
        if (str[0].equals("trzl_jgh")) {
            DcProjectMentionInformation pm = daoDcProjectMention.fetch(str[1]);
            filePath = POIFileUtil.getFilePathByType("提入资料_jgh",project_id)+pm.getMention_information_name()+".docx";
        } else if (str[0].equals("trzl_fjgh")){
            PcProjectFile pf = daoPcProjectFile.fetch(str[1]);
            if (null!=pf) {
                filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+pf.getRelativePaths();
            }
        } else if (str[0].equals("sjdy")) {
            DcProjectDesignCell pd = daoDcProjectDesignCell.fetch(str[1]);
            filePath = POIFileUtil.getFilePathByType("设计单元",project_id)+pd.getDesign_cell_table_name()+".docx";
        } else if(str[0].equals("sjps")){
            DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(str[1]);
            filePath = POIFileUtil.getFilePathByType("设计评审",project_id)+dcTemplateVersion.getTemplate_name()+".docx";
        } else {
            List<DcCompoundTemplate> ls = projectSjpsService.getTemplateListByIds(str[1]);
            if (ls.size()>0) {
                filePath = sysPath + ls.get(0).getTemplate_file_path();
            }else {
                filePath = "";
            }
        }
        log.debug("bag download。。。。。。"+filePath);
        System.out.println("download file sjps fjgh file--------------------------------"+filePath+"------------");
        //File newFile=new File(filePath);
        //DownloadFileUtil.webDownloadFileUtil(newFile,newFile.getName(),req,resp);
        DownloadFileUtil.fileStream(filePath, req, resp);
        //return newFile;
    }

    /**
     * 点击预览
     * */
    @At("/preview/?/?/?")
    @Ok("beetl:/projectRoot/pcCenter/pageOffice/merge_word.html")
    public NutMap preview(String project_id,String fileId,String fileType,HttpServletRequest request) {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        WordDocument docx = new WordDocument();
        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
        poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
        poCtrl.setSaveFilePage("/save");//设置处理文件保存的请求方法
        poCtrl.setTheme(ThemeType.Office2010);
        poCtrl.setWriter(docx);
        //打开word
        String filePath = "";
        if (fileType.equals("trzl_jgh")) {
            filePath = request.getContextPath()+"/projectCenter/sjps/downFile/"+"trzl_jgh__"+fileId+"/"+project_id;
        } else if (fileType.equals("sjdy")) {
            filePath = request.getContextPath()+"/projectCenter/sjps/downFile/"+"sjdy__"+fileId+"/"+project_id;
        } else {
            filePath = request.getContextPath()+"/projectCenter/sjps/downFile/"+"mb__"+fileId+"/"+project_id;
        }
        System.out.println(" preview file ---------------------------"+filePath);
        poCtrl.webOpen(filePath, OpenModeType.docNormalEdit,"张三");
        poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
        poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
        poCtrl.setJsFunction_BeforeDocumentClosed("Save");
        nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
        return nutMap;
    }

    /**
     * pageoffice保存
     * */
    @POST
    @At("/savefile/?/?")
    @Ok("json:full")
    public AjaxResult savefile(String project_id,String wjid,HttpServletRequest req,HttpServletResponse resp) {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        String path = POIFileUtil.getFilePathByType("设计评审",project_id);
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);
        FileSaver fs=new FileSaver(req,resp);
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        fs.saveToFile(path+dcTemplateVersion.getTemplate_name()+".docx");
        fs.close();
        return AjaxResult.success("success");
    }

    //导出设计评审
    @At("/exportWordData/?/?")
    public void exportWordData(String wjid , String project_id, HttpServletRequest req , HttpServletResponse rep){
        //查询设计单元 表名
        String path = POIFileUtil.getFilePathByType("设计评审",project_id);
        DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(wjid);
        File file = new File(path+dcTemplateVersion.getTemplate_code()+".docx");
        DownloadFileUtil.downLoadFile(file, dcTemplateVersion.getTemplate_name()+".docx", req, rep);
    }

    //打包下载
    @At("/BatchDownLoad/?")
    public void BatchDownLoad(String project_id, HttpServletRequest req , HttpServletResponse rep){
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        //获取设计评审资料库
        List<Map> list = projectSjpsService.getDcTemplateVersionList(nutMap);
        //获取这个阶段所有提入资料 里的非结构化文件
        List<NutMap> listNew = projectSjpsService.getMentionFjghByPhaseAndContentId(nutMap);
        //获取这个阶段所有提入资料 里的结构化文件
        List<NutMap> listNew2 = projectSjpsService.getMentionJghByPhaseAndContentId(nutMap);

        PcProjectInfo projectInfo = daoPcProjectData.fetch(project_id);
        //获取 所有 非结构化资料(车站表和上阶段审查意见)
        List<NutMap> trzl_fjgh = new ArrayList<NutMap>();

        //获取 结构化 旅客列车对数表
        List<NutMap> trzl_jgh = new ArrayList<NutMap>();

        if (projectInfo.getProject_design_content_name().equals("动车运用所")){
            for (int i=0;i<listNew.size();i++){
                String fileName = (String)listNew.get(i).get("mention_information_name");
                if (fileName.equals("车站表")){
                    listNew.get(i).put("mention_information_name","附件04 车站表");
                    trzl_fjgh.add(listNew.get(i));
                } else if (fileName.equals("上阶段审查意见")){
                    listNew.get(i).put("mention_information_name","附件01 上阶段审查意见");
                    trzl_fjgh.add(listNew.get(i));
                }
            }
            for (int i=0;i<listNew2.size();i++){
                String fileName = (String)listNew2.get(i).get("mention_information_name");
                if (fileName.equals("旅客列车对数表")){
                    listNew2.get(i).put("mention_information_name","附件05 旅客列车对数表");
                    trzl_jgh.add(listNew2.get(i));
                }
            }
        }

        List<File> fileList = new ArrayList<>();
        for (int i=0;i<list.size();i++) {//拿所有 设计评审资料库的文件
            String path = POIFileUtil.getFilePathByType("设计评审",project_id);
            Map maps = list.get(i);
            DcTemplateVersion dcTemplateVersion = projectSjpsService.getDcTemplateVersionById(maps.get("id").toString());
            File file = new File(path+dcTemplateVersion.getTemplate_name()+".docx");
            fileList.add(file);
        }

        for (int i=0;i<trzl_fjgh.size();i++) {//拿 车站表 和上阶段审查意见的文件
            String path = POIFileUtil.getFilePathByType("提入资料_fjgh",project_id);
            DcProjectMentionInformation mentionInformation = daoDcProjectMention.fetch(trzl_fjgh.get(i).get("id").toString());
            List<NutMap> fields = commonDao.getFieldByTableId("dc_mention_"+mentionInformation.getMention_information_code());
            for(int j=0;j<fields.size();j++){
                if(!fields.get(j).get("COLUMN_NAME").toString().equals("id") && !fields.get(j).get("COLUMN_NAME").toString().equals("project_id") && !fields.get(j).get("COLUMN_NAME").toString().equals("serial_number")){
                    QueryResult result = commonDao.findDataByTableName(new NutMap().addv("project_id",project_id).addv("table_name","dc_mention_"+mentionInformation.getMention_information_code()));
                    List <?> map = result.getList();
                    if (map.size()>0) {
                        NutMap m = (NutMap) map.get(0);
                        PcProjectFile file = daoPcProjectFile.fetch((String)m.get(fields.get(j).get("COLUMN_NAME").toString()));
                        if (null!=file && StringUtils.isNotEmpty(file.getId())){
                            File files = new File(path+file.getRelativePaths());
                            log.debug("bag download  jghwj。。。。。。"+path+file.getRelativePaths());
                            fileList.add(files);
                        }
                    }

                }
            }
        }

        for (int i=0;i<trzl_jgh.size();i++) {//拿 车站表 和上阶段审查意见的文件
            String path = POIFileUtil.getFilePathByType("提入资料_jgh",project_id);
            DcProjectMentionInformation mentionInformation = daoDcProjectMention.fetch(trzl_jgh.get(i).get("id").toString());
            File file = new File(path+mentionInformation.getMention_information_name()+".docx");
            log.debug("bag download  jghwj。。。。。。"+path+mentionInformation.getMention_information_code());
            fileList.add(file);
        }
        log.debug("bag download。。。。。。");
        DownloadFileUtil.batchDownLoadFile(fileList, projectInfo.getProject_name()+"设计评审文件包.zip", req, rep);



    }

}
